import {
  memo,
  MouseEventHandler,
  useCallback,
  useEffect,
  useMemo,
  useState,
} from 'react';
import type { FC, PropsWithChildren } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import { Button, message, Spin } from 'antd';
import logo from '@/assets/logo.png';
import { resAddressList } from '@/services/address';
import { resAlipay } from '@/services/alipay';
import {
  resAddOrders,
  resOrdersPost,
  resOrdersPreview,
  resOrdersReceive,
} from '@/services/orders';
import { cartSumState } from '@/store/cartStore';
import { RollbackOutlined } from '@ant-design/icons';
import { useRequest } from 'ahooks';
import { useRecoilValue } from 'recoil';
import AddressCard from '@/components/AddressCard';
import AddressFormModal from '@/components/AddressFormModal';
import { formatCarts, formatUrl } from '@/utils/format';

const OrderGroup: FC<PropsWithChildren<{ data: CartShow }>> = ({ data }) => {
  const shopSum = useMemo(() => {
    let sum = 0;
    data.carts.forEach((value) => {
      sum += value.num * value.goods?.price! * value.goods?.discount!;
    });
    return sum;
  }, [data]);
  return (
    <div className={'py-1'}>
      <div className={'flex items-start py-2 text-base '}>
        <img className={'w-5 h-5 mx-0.5'} src={logo} alt="" />{' '}
        <span className={'font-serif mr-2'}>商家:</span>{' '}
        <Link to={`/user_page/` + data.id}>{data.name}</Link>
      </div>
      <div className={'rounded-3xl overflow-hidden'}>
        {data.carts.length > 0
          ? data.carts.map((value) => <OrderItem key={value.id} data={value} />)
          : null}
      </div>
      <div className={'text-right pt-1.5'}>
        <span className={'border-b-2 border-blue-300 pb-0.5 border-dashed'}>
          店铺合计(包邮)
          <span className={'text-red-500 font-bold text-lg px-2'}>
            <em className={'text-sm'}>￥</em>
            {shopSum}
          </span>
        </span>
      </div>
    </div>
  );
};

const OrderItem: FC<PropsWithChildren<{ data: API.CartStruct }>> = ({
  data,
}) => {
  const navigate = useNavigate();

  return (
    <div
      className={
        'flex items-start justify-between p-2 border-gray-200 border-b text-center transition'
      }
    >
      <div
        className={'flex justify-center flex-1  mx-16 cursor-pointer'}
        onClick={() => {
          navigate(`/goods_detail/` + data.goods_id);
        }}
      >
        <img
          className={'w-12 h-18'}
          src={formatUrl(data.goods?.cover!)}
          alt=""
        />
        <div className={'text-left'}>
          <div className={'px-4 pb-2 pt-3 space-y-1.5'}>
            <div className={'text truncate'}>{data.goods?.title}</div>
            <div className={'truncate-2'}>{data.goods?.description}</div>
          </div>
        </div>
      </div>
      <div className={'space-y-2 w-[15%]'}>
        <div>
          <i className={'line-through text-gray-600'}>
            <em className={'text-xs px-0.5'}>￥</em>
            {data.goods?.discount! < 1 ? data.goods?.price : null}
          </i>
        </div>
        <div>
          <strong className={'text-blue-600 text-lg'}>
            <em className={'text-xs px-0.5'}>￥</em>
            {data.goods?.price! * data.goods?.discount!}
          </strong>
        </div>
      </div>
      <div className={'w-[15%]'}>{data.num}</div>
      <div className={'text-lg w-[15%] text-red-500 font-bold font-serif'}>
        <em className={'text-xs px-0.5'}>￥</em>
        <span>{data.num * data.goods?.price! * data.goods?.discount!}</span>
      </div>
    </div>
  );
};

const OrdersPreview: FC<PropsWithChildren<{}>> = () => {
  const { data: addresses, run } = useRequest(resAddressList);
  const [addressId, setAddressId] = useState(0);
  useEffect(() => {
    if (addresses) {
      setAddressId(addresses?.find((value) => Boolean(value.is_default))?.id!);
    }
  }, [addresses]);

  const address = useMemo(() => {
    return addresses?.find((value) => value.id === addressId);
  }, [addresses, addressId]);

  const { data, loading: previewLoading } = useRequest(resOrdersPreview);

  const { runAsync: addOrders, loading: AddOrdersLoading } = useRequest(
    resAddOrders,
    {
      manual: true,
    }
  );

  const showOrders = useMemo(() => {
    return data && formatCarts(data.carts);
  }, [data]);

  const navigate = useNavigate();

  const { runAsync: alipay, loading: alipayLoading } = useRequest(resAlipay, {
    manual: true,
  });

  const onAddOrdersHandler = useCallback(() => {
    addOrders({ address_id: addressId }).then((value) => {
      message.success('提交订单成功');
      alipay({
        orders_ids: Object.values(value).map((v) => {
          return v.id;
        }),
      }).then((value) => {
        location.href = value;
      });
    });
  }, [addressId]);

  return (
    <Spin spinning={alipayLoading} size={'large'}>
      <section className={''}>
        <div className={'mb-5'}>
          <div className={'p-3 text-base font-bold'}>选择收货地址</div>
          <div>
            {addresses ? (
              <AddressCard
                checkedValue={addressId!}
                onChange={(id) => {
                  setAddressId(id);
                }}
                data={addresses}
                run={run}
              />
            ) : null}
          </div>
        </div>
        <div>
          <div className={'p-2 text-base font-bold'}>确认订单信息</div>
          <div className={'px-5 py-3'}>
            <div
              className={
                'flex pb-1 items-center justify-between text-center border-b-2 border-blue-200'
              }
            >
              <div className={'flex-1'}>商品信息</div>
              <div className={'w-[15%]'}>单价</div>
              <div className={'w-[15%]'}>数量</div>
              <div className={'w-[15%]'}>小计</div>
            </div>
            <div className={'mt-3'}>
              <Spin spinning={previewLoading} />
              {showOrders &&
                showOrders.length > 0 &&
                showOrders.map((value) => (
                  <OrderGroup key={value.id} data={value} />
                ))}
            </div>
            <div>
              {address && (
                <AddOrdersCard
                  address={address}
                  onClick={onAddOrdersHandler}
                  loading={AddOrdersLoading}
                />
              )}
            </div>
          </div>
        </div>
      </section>
    </Spin>
  );
};

const AddOrdersCard: FC<
  PropsWithChildren<{
    address: API.AddressStruct;
    onClick: MouseEventHandler;
    loading: boolean;
  }>
> = ({ address, onClick, loading }) => {
  const navigate = useNavigate();
  const cartSum = useRecoilValue(cartSumState);
  return (
    <div className={'mt-10'}>
      <div
        className={
          'border space-y-1.5 border-blue-500 px-6 py-4 max-w-fit ml-auto text-right'
        }
      >
        <div>
          <strong>实付款：</strong>
          <span className={'text-red-500 font-bold text-3xl'}>
            <em className={'text-base'}>￥</em>
            {cartSum}
          </span>
        </div>
        <div className={'space-x-2 text-sm'}>
          <strong>寄送至：</strong>
          <span>{address.province}</span>
          <span>{address.city}</span>
          <span>{address.county}</span>
          <span>{address.address}</span>
        </div>
        <div className={'space-x-2 text-sm'}>
          <strong> 收货人：</strong>
          <span>{address.name}</span>
          <span>{address.phone}</span>
        </div>
      </div>
      <div className={'flex items-center justify-end'}>
        <Button
          type={'link'}
          icon={<RollbackOutlined />}
          onClick={() => {
            navigate('/cart');
          }}
          className={'mr-16'}
        >
          返回购物车
        </Button>
        <Button
          size={'large'}
          onClick={onClick}
          loading={loading}
          type={'primary'}
          disabled={cartSum === 0}
        >
          提交订单
        </Button>
      </div>
    </div>
  );
};

export default memo(OrdersPreview);
